﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace Enough.Converter
{
    public class ComparisonToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter == null)
            {
                return true;
            }
            string param = parameter.ToString();
            if (param.StartsWith("=="))
            {
                param = param.Substring(2).Trim();
                return param.Equals(value.ToString());
            }
            if (param.StartsWith("="))
            {
                param = param.Substring(1).Trim();
                return param.Equals(value.ToString());
            }
            double valueDouble;
            if (value is double)
            {
                valueDouble = (double)value;
            }
            else if (value is float)
            {
                valueDouble = (float)value;
            }
            else if (value is long)
            {
                valueDouble = (long)value;
            }
            else if (value is int)
            {
                valueDouble = (int)value;
            }
            else if (value is short)
            {
                valueDouble = (short)value;
            }
            else if (!double.TryParse(value.ToString(), out valueDouble))
            {
                return false;
            }
            double compare;
            if (param.StartsWith(">="))
            {
                param = param.Substring(2).Trim();
                if (double.TryParse(param, out compare))
                {
                    return valueDouble >= compare;
                }
            }
            if (param.StartsWith("<="))
            {
                param = param.Substring(2).Trim();
                if (double.TryParse(param, out compare))
                {
                    return valueDouble <= compare;
                }
            }
            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
